package com.sweet.store;

import com.sweet.entity.TokenObj;
import com.sweet.entity.User;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import org.mapdb.DB;
import org.mapdb.DBMaker;

import java.io.File;
import java.util.Map;


public class TokenStore implements ITransaction {
  private static final TokenStore TOKEN_STORE = new TokenStore();
  private static final String BASE_PATH = "db/";
  private static final String TOKEN_DB_PATH = BASE_PATH + "token.db";
  private static final DB TOKEN_DB = DBMaker.newFileDB(new File(TOKEN_DB_PATH)).closeOnJvmShutdown().make();

  private static final Map<String, String> TOKEN_MAP = TOKEN_DB.getTreeMap("token-map");

  public static TokenStore instance() {
    return TOKEN_STORE;
  }

  public Future<User> saveToken(String token, User user, Vertx vertx) {
    Future<User> future = Future.future();
    vertx.executeBlocking(f -> {
      TOKEN_MAP.put(token, new TokenObj(token, null, user).toJson());
      commit();
      f.complete(user);
    }, future);
    return future;
  }

  public Future<TokenObj> findKey(String token, Vertx vertx) {
    Future<TokenObj> future = Future.future();
    vertx.executeBlocking(f -> f.complete(TokenObj.fromJson(TOKEN_MAP.get(token))), future);
    return future;
  }

  public Future<Void> remove(String token, Vertx vertx) {
    Future<Void> future = Future.future();
    vertx.executeBlocking(f -> {
      TOKEN_MAP.remove(token);
      commit();
      f.complete();
    }, future);
    return future;
  }

  @Override
  public void commit() {
    TOKEN_DB.commit();
  }

  @Override
  public void close() {
    TOKEN_DB.commit();
    if (!TOKEN_DB.isClosed())
      TOKEN_DB.close();
  }
}
